/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.push.notifications;


import static com.push.notifications.CommonUtilities.displayMessage;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;

/**
 * IntentService responsible for handling GCM messages.
 */
public class GCMIntentService extends GCMBaseIntentService {
	
	 static boolean AppInterrupt= true;
	 public static boolean news_islive= false;
	 public static boolean web_islive= false;
    @SuppressWarnings("hiding")
    private static final String TAG = "GCMIntentService";
  
    public GCMIntentService() {
        super(Definitions.SENDER_ID);       
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context, getString(R.string.gcm_registered));
        if(!registrationId.equals(""))
        {
        	ServerUtilities.register(context, registrationId,"-1");
        	NotificationActivity.regId = registrationId;
        }         
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        if (GCMRegistrar.isRegisteredOnServer(context)) {
            ServerUtilities.unregister(context, registrationId);
        } else {
            // This callback results from the call to unregister made on
            // ServerUtilities when the registration to the server failed.
            Log.i(TAG, "Ignoring unregister callback");
        }
    }

    
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        //  hoc kill old popup-message
        if (GCMIntentService.news_islive)
        {
        	popupNews.han_popupNews.sendEmptyMessage(0);
        }
        if (GCMIntentService.web_islive)
        {
        	popupWebview.han_popupWebview.sendEmptyMessage(0);
        }
        String regId = GCMRegistrar.getRegistrationId(context);
        //getExpiredDate(regId);
    	//create a thread 
    	//createThreadExpiredDate();
        String userPush = intent.getExtras().getString("push");
        String sThum = intent.getExtras().getString("icon");
    	String sIdContent = intent.getExtras().getString("id");
    	
    	int idContent = 0;
    	try{
    		idContent = Integer.parseInt(sIdContent);
    	}
    	catch(NumberFormatException e) {
    		idContent = -1;
        }
    	String sLink = intent.getExtras().getString("link");
    	String subTitle = intent.getExtras().getString("subtitle");
    	
    	String sTitle = intent.getExtras().getString("title");
    	String sDesc = intent.getExtras().getString("desc");
    	String sCommand = intent.getExtras().getString("command"); 
    	int nCatalogId = -1;
        if(userPush != null && userPush.equalsIgnoreCase("admin")) //Case Administrator
        {
        	if(sCommand.equalsIgnoreCase("title"))//guest with Id content if command = title
        	{
        		popupNews.bAdmin = true;
	        	if(idContent != -1) //Case id_content
	    		{
	        		popupNews.sUrl = Definitions.LINK_ADMIN + idContent;        	
	        		popupNews.bLink = false;
	    		}
	        	else // with link 
	        	{
	        		popupNews.sUrl = sLink;
	        		popupNews.bLink = true;
	        	}
        	}
        	else
        	{
	        	popupWebview.bAdmin = true;
	        	if(idContent != -1) //Case id_content
	    		{
	        		popupWebview.sUrl = Definitions.LINK_ADMIN + idContent;        	
	        		popupWebview.bLink = false;
	    		}
	        	else // with link 
	        	{
	        		popupWebview.sUrl = sLink;
	    			popupWebview.bLink = true;
	        	}
        	}
       
        }
        else  //Case guest
        {
        	popupNews.bAdmin = false;
        	if(sCommand.equalsIgnoreCase("title"))//guest with Id content if command = title
        	{
        		
        		if(idContent != -1) //Case id_content
        		{
        			popupNews.sUrl = Definitions.LINK_CONTENT + idContent;
        			popupNews.bLink = false;
        		}
        		else //Case link
        		{
        			popupNews.sUrl = sLink;
        			popupNews.bLink = true;
        		}
        		
        		
        	}
        	else  // not newspaper
        	{        	
        		//contain content
        	}
        	
        	String sCatalogId =  intent.getExtras().getString("extendId");
        	nCatalogId = Integer.parseInt(sCatalogId);
        	
        	//Addition insert to data base
        	if(idContent > 0)  //not link
        		databaseWrapper.insertNews(context,nCatalogId, sTitle,sDesc,sThum,idContent);
        	
        }
        
        
        String title = context.getString(R.string.app_name);
        // add content here
        //Show new popup-message  
        if(sCommand.equalsIgnoreCase("title"))//guest with Id content if command = title
    	{
        	popupNews.sCommand = sCommand;
        	popupNews.titleDialog = sTitle;
        	popupNews.descriptonDialg = subTitle;
        	popupNews.sortContentDialog = sDesc;
        	popupNews.urlImage = Definitions.LINK_TEST_DOWNLOAD +sThum;
        	Intent dialogNewIntent = new Intent(getBaseContext(), popupNews.class);
        	dialogNewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             
             getApplication().startActivity(dialogNewIntent); 
    	}
        else 
        {
        	String link = "http://vipmobi.net:8010/push/xoso.htm";
        	if(sCommand.equalsIgnoreCase("gold"))
        		link = "http://vipmobi.net:8010/push/gold.htm";
        	popupWebview.sCommand = sCommand;
            popupWebview.titleDialog = Definitions.TITLE_DIALOG;
            popupWebview.descriptonDialg = "";
            popupWebview.sortContentDialog = sDesc;
            popupWebview.urlImage = null;
            popupWebview.sUrl =  link;         
            
            
        	Intent dialogIntent = new Intent(getBaseContext(), popupWebview.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             
            getApplication().startActivity(dialogIntent); 
            
            databaseWrapper.updateExpression(this, nCatalogId, link, sDesc);
        }
                      
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        ///generateNotification(context, message); thien_vv
    }

    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, getString(R.string.gcm_recoverable_error,
                errorId));
        return super.onRecoverableError(context, errorId);
    }
  
}
